<script setup lang="ts">
import type { PrickerConfig, ColumnsItem } from '@/types/pricker';
import { inject, reactive, watch, watchEffect, unref, computed } from 'vue';

// 是否为大屏应用
const largenScreen = inject<boolean>('largenScreen');
// 是否为只读状态
const injectReadOnly = inject<boolean>('readOnly', false);

const props = withDefaults(
  defineProps<{
    modelValue: string;
    columns: ColumnsItem[];
    label: string;
    name: string;
    teleport?: string;
    propsReadOnly?: boolean;
  }>(),
  {
    modelValue: '',
    columns: () => [],
    label: '',
    name: '',
    teleport: '',
    propsReadOnly: false,
  }
);

const readOnly = computed(() => unref(injectReadOnly) || props.propsReadOnly);

const emit = defineEmits<{
  (e: 'update:model-value', value: string): void;
  (e: 'onConfirm', value: string): void;
}>();

const priceConfig: PrickerConfig = reactive({
  show: false,
  value: [],
  showValue: () => priceConfig.columns.find((v) => v.value === props.modelValue)?.text || '',
  onConfirm({ selectedOptions }) {
    priceConfig.show = false;
    emit('update:model-value', selectedOptions[0].value);
    emit('onConfirm', selectedOptions[0].value);
  },
  columns: props.columns,
});

watch(
  () => props.columns,
  () => {
    priceConfig.columns = props.columns;
  }
);

watchEffect(() => {
  priceConfig.value = [props.modelValue];
});

const showPicker = () => {
  if (!unref(readOnly)) {
    priceConfig.show = true;
  }
};

defineExpose({
  setColumn(columnKey: string, key: keyof ColumnsItem, value: any) {
    const el = priceConfig.columns.find((v) => v.value === columnKey);
    if (el) {
      // @ts-ignore
      el[key] = value;
    }
  },
  setValue(value: PrickerConfig['value']) {
    priceConfig.value = value;
  },
});
</script>
<template>
  <van-field
    v-bind="$attrs"
    label-class="u_label"
    :model-value="priceConfig.showValue()"
    :is-link="!readOnly"
    readonly
    :name="name"
    :label="label"
    :placeholder="`点击选择${label}`"
    :rules="[{ required: true, message: `请选择${label}` }]"
    @click="showPicker"
  />

  <!-- 弹框 -->
  <van-popup
    v-model:show="priceConfig.show"
    position="bottom"
    safe-area-inset-bottom
    round
    :lock-scroll="!largenScreen"
    :teleport="teleport"
  >
    <van-picker
      v-model="priceConfig.value"
      :columns="priceConfig.columns"
      @confirm="priceConfig.onConfirm"
      @cancel="priceConfig.show = false"
    />
  </van-popup>
</template>
<style lang="less" scoped></style>
